#!/usr/bin/env python
# encoding: UTF-8

from db_cleanup import get_tables

import sys
import os, os.path
import sqlite3

def main(argv):
    if len(argv) < 2:
        print "Usage: %s database [folder_where_to_create_files]" % argv[0]
        print
        print "Extracts information about contacts from the db"
        print "and saves it to files in the format of hbplus."

    directory = "."
    if len(argv) > 2:
        directory = argv[2]

    db_name = argv[1]
    tables = get_tables(db_name)

    conn = sqlite3.connect(db_name)
    cur = conn.cursor()

    
    for (contacts, atoms) in tables:
        filename = os.path.join(directory, contacts + ".all")
        f = open(filename, "w")
        cur.execute("""
        SELECT a.chain, a.residue, a.insertion, a.amino, a.atom,
               d.chain, d.residue, d.insertion, d.amino, d.atom,
                directness, type, cat_a, cat_d FROM
            %(contacts)s c, %(atoms)s a, %(atoms)s d
        WHERE
            c.donor_id = d.id
            AND c.acceptor_id = a.id
        """ % {"contacts" : contacts, "atoms" : atoms})
        print >> f, "// acceptor = a, donor = d"
        print >> f, "a.chain, a.residue, a.insertion, a.amino, a.atom, d.chain, d.residue, d.insertion, d.amino, d.atom, directness, type, cat_a, cat_d"
        for row in cur:
            print >> f, ",".join(str(x) for x in row)
        f.close()

if __name__ == "__main__":
    main(sys.argv)
